<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AccountingController
 *
 * @author Poh Nean
 */
class AccountingController extends PsController
{

	public $defaultAction = 'invoice';
	public $layout = 'manage';

	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'roles' => array('ManageModule.Accounting'),
					),
						), parent::accessRules());
	}

	public function moduleAccessRules()
	{
		return array(
			array('Propsage.Accounting.Commission', array('paymentVouchers')),
			array('Propsage.Accounting'),
		);
	}

	public function actionIndex()
	{
		$this->render('index');
	}

	public function actionInvoice()
	{
		$agency = $this->loadAgency();

		if ($agency->settings == null) {
			$agency->settings = array();
		}

		if (!empty($_POST['AgencySetting'])) {
			foreach ($_POST['AgencySetting'] as $key => $value) {
				$agency->setSetting($key, $value);
			}

			if ($agency->save(true, array('settings'))) {
				PsSystemMessage::add('Invoice settings updated.', 'success');
				$this->refresh();
			}
		}

		$data = array();
		$data['agency'] = $agency;
		$this->render('invoice', $data);
	}

	public function actionChartOfAccounts($view = '', $pagesize = 50)
	{
		if (isset($_POST['chart_of_accounts_grid_cid'])) {
			$action = $_POST['action'];

			if ($action == 'Delete') {
				$glAccountIds = $_POST['chart_of_accounts_grid_cid'];

				$deleteCount = 0;
				$failed = array();

				if (!empty($glAccountIds)) {
					foreach ($glAccountIds as $glAccountId) {
						$glAccount = $this->loadGlAccount($glAccountId);

						if ($glAccount->hasGlTransactionDetails()) {
							$failed[] = $glAccount;
						} else {
							if ($glAccount->delete()) {
								$deleteCount++;
							}
						}
					}
				}

				if ($deleteCount > 0 && empty($failed)) {
					PsSystemMessage::add($deleteCount . ' accounts deleted.', 'success');
				} else {
					PsSystemMessage::add($deleteCount . ' accounts deleted. ' . count($failed) . ' account(s) have transactions cannot be deleted.', 'error', false);
				}

				$this->redirect(array('modules/accounting/chartOfAccounts'));
			}
		}

		$criteria = new CDbCriteria();
		$criteria->compare('t.gl_account_type_code', $view);
		$criteria->compare('t.owner_party_id', Yii::app()->user->model->agency->party_id);

		$dataProvider = new CActiveDataProvider('GlAccount');
		$dataProvider->setCriteria($criteria);
		$dataProvider->setPagination(array('pageSize' => $pagesize));

		$data = array();
		$data['view'] = $view;
		$data['dataProvider'] = $dataProvider;

		$this->render('chart_of_accounts', $data);
	}

	public function actionAddDefaultAccounts()
	{
		// check if agency has account already
		$criteria = new CDbCriteria();
		$criteria->compare('t.owner_party_id', Yii::app()->user->model->agency->party_id);

		$glAccountsCount = GlAccount::model()->count($criteria);

		if ($glAccountsCount > 0) {
			PsSystemMessage::add('Invalid Action', 'error');
		} else {
			$defaultGlAccounts = GlAccount::model()->findAllByAttributes(array(
				'owner_party_id' => null
					));

			if (!empty($defaultGlAccounts)) {
				$tx = Yii::app()->db->beginTransaction();
				try {
					foreach ($defaultGlAccounts as $defaultGlAccount) {
						$glAccount = new GlAccount;

						$glAccount->gl_account_type_code = $defaultGlAccount->gl_account_type_code;
						$glAccount->name = $defaultGlAccount->name;
						$glAccount->description = $defaultGlAccount->description;
						$glAccount->code = $defaultGlAccount->code;
						$glAccount->balance = $defaultGlAccount->balance;
						$glAccount->owner_party_id = Yii::app()->user->model->agency->party_id;

						$glAccount->save();
					}

					$tx->commit();
				} catch (CException $e) {
					$tx->rollback();
				}
			}
		}


		$this->redirect(array('modules/accounting/chartOfAccounts'));
	}

	public function actionAddAccount()
	{
		$glAccount = new GlAccount();

		if (isset($_POST['GlAccount'])) {
			$glAccount->attributes = $_POST['GlAccount'];
			$glAccount->owner_party_id = Yii::app()->user->model->agency->party_id;

			if ($glAccount->save()) {
				PsSystemMessage::add('Account Added.', 'success');
				$this->redirect(array('modules/accounting/chartOfAccounts'));
			}
		}

		$data = array();
		$data['glAccount'] = $glAccount;

		$this->render('account_create', $data);
	}

	public function actionAddTax()
	{
		$taxType = new TaxType();
		$tax = new Tax();
		$taxType->owner_party_id = Yii::app()->user->model->agency->party_id;
		$tax->owner_party_id = Yii::app()->user->model->agency->party_id;

		if (isset($_POST['TaxType'], $_POST['Tax'])) {
			$taxType->attributes = $_POST['TaxType'];
			$tax->attributes = $_POST['Tax'];

			$taxType->owner_party_id = Yii::app()->user->model->agency->party_id;
			$tax->owner_party_id = Yii::app()->user->model->agency->party_id;

			$valid = $taxType->validate();

			if ($valid) {
				$taxTypeStatus = $taxType->save(false);
				$newId = $taxType->id;
				$tax->tax_type_id = $newId;
				$taxStatus = $tax->save(false);

				if ($taxTypeStatus && $taxStatus) {
					PsSystemMessage::add('Tax Added.', 'success');
					$this->redirect(array('modules/accounting/taxes'));
				}
			}
		}
		$data = array();
		$data['taxType'] = $taxType;
		$data['tax'] = $tax;

		$this->render('tax_create', $data);
	}

	public function actionEditTax($tax_type_id)
	{

		$previousTax = Tax::model()->ofOwnerParty(Yii::app()->user->model->agency->party_id)->findAll(array(
			'condition' => 'tax_type_id=:x',
			'params' => array(':x' => $tax_type_id),
			'order' => 'id DESC',
			'limit' => 1));


		$previousTax = $previousTax[0];

		$tax = new Tax();
		$tax->owner_party_id = Yii::app()->user->model->agency->party_id;
		$tax->tax_type_id = $tax_type_id;

		if (isset($_POST['Tax'])) {
			$tax->attributes = $_POST['Tax'];
			$tax->owner_party_id = Yii::app()->user->model->agency->party_id;

			$previousEndDate = strtotime('-1 day', strtotime($tax->from_date));
			$previousTax->to_date = date('Y-m-j', $previousEndDate);

			if ($tax->validate()) {
				if ($tax->save(false)) {
					$previousTax->save();
					PsSystemMessage::add('Tax Updated.', 'success');
					$this->redirect(array('modules/accounting/taxes'));
				}
			}
		}
		$data = array();
		$data['tax'] = $tax;

		$this->render('tax_edit', $data);
	}

	public function actionAjaxAddTaxType()
	{
		$newTaxTypeName = $_POST['name'];

		$taxType = new TaxType();
		$taxType->name = $newTaxTypeName;
		$taxType->owner_party_id = Yii::app()->user->model->agency->party_id;

		if ($taxType->save()) {
			$taxTypes = TaxType::model()->ofOwnerParty($taxType->owner_party_id)->findAll();
			$options = array();
			foreach ($taxTypes as $type) {
				$options[$type->id] = $type->name;
			}
		}
	}

	public function actionUpdateAccount($id)
	{
		$glAccount = $this->loadGlAccount($id);

		if (isset($_POST['GlAccount'])) {
			$glAccount->attributes = $_POST['GlAccount'];

			if ($glAccount->save()) {
				PsSystemMessage::add('Account Updated.', 'success');
				$this->redirect(array('modules/accounting/chartOfAccounts'));
			}
		}

		$data = array();
		$data['glAccount'] = $glAccount;

		$this->render('account_update', $data);
	}

	public function actionDeleteAccount($id)
	{
		$response = array();

		$glAccount = $this->loadGlAccount($id);

		if ($glAccount->hasGlTransactionDetails()) {
			$response['success'] = false;
			$response['errorMsg'] = 'Account cannot be deleted. There are transactions associated to this account.';
		} else {
			if ($glAccount->delete()) {
				$response['success'] = true;
			}
		}

		print(json_encode($response));
	}

	public function actionTaxes()
	{
		$tax = new Tax('search');

		if (isset($_GET['Tax'])) {
			$tax->attributes = $_GET['Tax'];
		}

		$data = array();
		$data['tax'] = $tax;

		$this->render('taxes', $data);
	}

	public function actionTemplates()
	{
		$template = new Template('search');
		$template->unsetAttributes();

		if (isset($_GET['Template'])) {
			$template->attributes = $_GET['Template'];
		}
		$dataProvider = $template->ofCurrentAgency()->search($_GET['pagesize']);

		$criteria = $dataProvider->getCriteria();
		$criteria->addInCondition('type', array('Invoice', 'Receipt', 'Payment Voucher'));
		$dataProvider->setCriteria($criteria);


		$data = array();
		$data['dataProvider'] = $dataProvider;
		$data['template'] = $template;

		$this->render('templates', $data);
	}

	public function loadGlAccount($id)
	{
		$glAccount = GlAccount::model()->ofCurrentAgency()->findByPk($id);

		if ($glAccount == null) {
			throw new PsPageNotFoundException();
		}

		return $glAccount;
	}

	public function loadAgency()
	{
		return Yii::app()->user->getSelectedAgency();
	}

	public function getDataProviderTax(Tax $tax)
	{
		$criteria = new CDbCriteria;
		$criteria->condition = 't.owner_party_id = :owner_party_id AND t.id = (SELECT MAX(id) FROM tax AS b WHERE b.tax_type_id = t.tax_type_id)';
		$criteria->params = array(
			':owner_party_id' => Yii::app()->user->model->agency->party_id
		);
		$criteria->with = array('taxType');

		$criteria->compare('t.rate', $tax->rate, true);
		$criteria->compare('t.from_date', $tax->from_date, true);
		$criteria->compare('t.to_date', $tax->to_date, true);
		$criteria->compare('taxType.name', $tax->taxTypeName, true);

		$dataProvider = new CActiveDataProvider('Tax', array(
					'criteria' => $criteria,
					'pagination' => array(
						'pageSize' => (isset($_GET['pagesize']) ? $_GET['pagesize'] : 10),
					)
				));


		return $dataProvider;
	}
	
	public function actionSetting()
	{
		$agency = $this->loadAgency();

		if ($agency->settings == null) {
			$agency->settings = array();
		}

		if (!empty($_POST['AgencySetting'])) {
			foreach ($_POST['AgencySetting'] as $key => $value) {
				$agency->setSetting($key, $value);
			}

			if ($agency->save(true, array('settings'))) {
				PsSystemMessage::add('Settings updated.', 'success');
				$this->refresh();
			}
		}

		$data = array();
		$data['agency'] = $agency;
		$this->render('setting', $data);
	}


	public function actionPaymentVouchers() {
		$data = array();

		$agency = Yii::app()->user->model->agency;

		$data['agency'] = $agency;
		if ($agency->settings == null) {
			$agency->settings = array();
		}

		if (!empty($_POST['AgencySetting'])) {
			foreach ($_POST['AgencySetting'] as $key => $value) {
				$agency->setSetting($key, $value);
			}

			if ($agency->save(true, array('settings'))) {
				PsSystemMessage::add('Your changes have been saved.', 'success');
				$this->refresh();
			}
		}

		$this->render('paymentVouchers', $data);
	}
}

?>
